package core

import (
	"github.com/casbin/casbin/v2"
	"github.com/casbin/casbin/v2/util"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	_ "github.com/go-sql-driver/mysql"
	"strings"
)



func Casbin() *casbin.Enforcer {
	var modelPath string = CF.Casbin // "./rbac_model.conf"
	//path, _ := os.Getwd()
	//fmt.Printf("当前路径 %v\n", path)
	// Initialize a Gorm adapter and use it in a Casbin enforcer:
	// The adapter will use the MySQL database named "casbin".
	// If it doesn't exist, the adapter will create it automatically.
	// You can also use an already existing gorm instance with gormadapter.NewAdapterByDB(gormInstance)
	a, err := gormadapter.NewAdapterByDB(DB) // Your driver and data source.
	if err != nil {
		//panic("Casbin连接数据库失败")
		LG.Panic("Casbin连接数据库失败")
		return nil
	}
	e, err := casbin.NewEnforcer(modelPath, a)
	if err != nil {
		//s := filepath.Join(path, "rbac_model.conf")
		//fmt.Printf(s)
		LG.Panic("Casbin加载模型失败")
		return nil
	}

	// 添加匹配 /api/v1/resources/:id的函数
	e.AddFunction("ParamMatch", ParamMatchFunc)

	// Load the policy from Db.
	if err = e.LoadPolicy(); err != nil {
		LG.Panic("Casbin加载策略失败")
		return nil
	}

	return e
}

func ParamMatch(key1 string, key2 string) bool {
	noparam := strings.Split(key1, "?")[0]
	return util.KeyMatch2(noparam, key2)
}

func ParamMatchFunc(args ...interface{}) (interface{}, error) {
	name1 := args[0].(string)
	name2 := args[1].(string)

	return (bool)(ParamMatch(name1, name2)), nil
}
